<template>
  <div class="advanced-table-container">
    <!-- 工具栏 -->
    <div v-if="showToolbar" class="table-toolbar">
      <div class="toolbar-left">
        <slot name="toolbar-left"></slot>
      </div>
      <div class="toolbar-right">
        <el-button 
          v-if="showRefresh" 
          :icon="Refresh" 
          @click="handleRefresh"
          :loading="loading"
        >
          刷新
        </el-button>
        <el-button 
          v-if="showColumnSettings" 
          :icon="Setting" 
          @click="showColumnSettingsDialog = true"
        >
          列设置
        </el-button>
        <slot name="toolbar-right"></slot>
        
        <!-- 视图切换 -->
        <el-button-group v-if="showViewToggle" class="view-toggle-group">
          <el-button 
            :type="viewMode === 'table' ? 'primary' : 'default'" 
            @click="setViewMode('table')"
          >
            <el-icon><List /></el-icon>表格
          </el-button>
          <el-button 
            :type="viewMode === 'card' ? 'primary' : 'default'" 
            @click="setViewMode('card')"
          >
            <el-icon><Grid /></el-icon>卡片
          </el-button>
        </el-button-group>
      </div>
    </div>

    <!-- 表格视图 -->
    <div v-show="viewMode === 'table'" class="table-view">
      <el-table
        ref="tableRef"
        :data="tableData"
        :loading="loading"
        :row-key="rowKey"
        :default-sort="defaultSort"
        :selected="selectedRows"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        @row-click="handleRowClick"
        v-bind="$attrs"
      >
        <template v-for="column in visibleColumns" :key="column.prop">
          <!-- 处理选择列 -->
          <el-table-column
            v-if="column.type === 'selection'"
            type="selection"
            :width="column.width || 50"
            :fixed="column.fixed"
            v-bind="column.attrs"
          />
          <!-- 处理其他列 -->
          <el-table-column
            v-else
            :prop="column.prop"
            :label="column.label"
            :width="column.width"
            :min-width="column.minWidth"
            :fixed="column.fixed"
            :sortable="column.sortable"
            :align="column.align || 'left'"
            :header-align="column.headerAlign"
            :class-name="column.className"
            v-bind="column.attrs"
          >
            <template #default="scope">
              <!-- 自定义单元格渲染 -->
              <template v-if="column.render">
                <component 
                  :is="column.render" 
                  :row="scope.row" 
                  :column="column" 
                  :index="scope.$index"
                />
              </template>
              <!-- 插槽渲染 -->
              <template v-else-if="column.slot">
                <slot 
                  :name="column.slot" 
                  :row="scope.row" 
                  :column="column" 
                  :index="scope.$index"
                />
              </template>
              <!-- 默认渲染 -->
              <template v-else>
                {{ getColumnValue(scope.row, column) }}
              </template>
            </template>
          </el-table-column>
        </template>
      </el-table>

      <!-- 分页 -->
      <div v-if="showPagination" class="table-pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="pagination.pageSizes"
          :layout="pagination.layout"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 卡片视图 -->
    <div v-show="viewMode === 'card'" class="card-view">
      <el-row :gutter="16">
        <el-col 
          v-for="(row, index) in tableData" 
          :key="getRowKey(row, index)"
          v-bind="cardLayout"
        >
          <div class="card-item" @click="handleCardClick(row, index)">
            <slot name="card" :row="row" :index="index">
              <!-- 默认卡片内容 -->
              <el-card shadow="hover">
                <div v-for="column in visibleColumns" :key="column.prop" class="card-field">
                  <div class="field-label">{{ column.label }}:</div>
                  <div class="field-value">
                    <template v-if="column.render">
                      <component 
                        :is="column.render" 
                        :row="row" 
                        :column="column" 
                        :index="index"
                      />
                    </template>
                    <template v-else-if="column.slot">
                      <slot 
                        :name="column.slot" 
                        :row="row" 
                        :column="column" 
                        :index="index"
                      />
                    </template>
                    <template v-else>
                      {{ getColumnValue(row, column) }}
                    </template>
                  </div>
                </div>
              </el-card>
            </slot>
          </div>
        </el-col>
      </el-row>

      <!-- 卡片视图分页 -->
      <div v-if="showPagination" class="table-pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="pagination.pageSizes"
          :layout="pagination.layout"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 列设置对话框 -->
    <el-dialog
      v-if="showColumnSettings"
      v-model="showColumnSettingsDialog"
      title="列设置"
      width="600px"
    >
      <div class="column-settings">
        <el-checkbox 
          v-model="showAllColumns" 
          @change="toggleAllColumns"
          class="select-all"
        >
          全选
        </el-checkbox>
        <el-divider />
        <el-checkbox-group v-model="selectedColumns">
          <el-row :gutter="16">
            <el-col 
              v-for="column in allColumns" 
              :key="column.prop"
              :span="12"
            >
              <el-checkbox 
                :value="column.prop" 
                :disabled="!!column.fixed"
              >
                {{ column.label }}
                <el-tag v-if="column.fixed" size="small" type="info">固定</el-tag>
              </el-checkbox>
            </el-col>
          </el-row>
        </el-checkbox-group>
      </div>
      <template #footer>
        <el-button @click="showColumnSettingsDialog = false">取消</el-button>
        <el-button type="primary" @click="applyColumnSettings">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { 
  ref, 
  computed, 
  watch, 
  onMounted
} from '@vue/runtime-core'
import { Refresh, Setting, List, Grid } from '@element-plus/icons-vue'
import BaseTable from './BaseTable.vue'

// 继承BaseTable的props
interface Column {
  key?: string
  prop?: string
  label?: string
  title?: string
  width?: string | number
  minWidth?: string | number
  fixed?: boolean | 'left' | 'right'
  sortable?: boolean | 'custom'
  sortOrders?: ('ascending' | 'descending')[]
  filters?: Array<{ text: string; value: any }>
  filterMethod?: (value: any, row: any, column: any) => boolean
  filterMultiple?: boolean
  showOverflowTooltip?: boolean
  align?: 'left' | 'center' | 'right'
  headerAlign?: 'left' | 'center' | 'right'
  className?: string
  labelClassName?: string
  visible?: boolean
  formatter?: (value: any, row: any, column: any, index: number) => any
  group?: string
  type?: string
  attrs?: any
}

interface Props {
  // 基础属性
  data?: any[]
  columns?: Column[]
  loading?: boolean
  rowKey?: string | ((row: any) => string)
  defaultSort?: { prop: string; order: string }
  selectedItems?: any[]
  
  // 分页属性
  pagination?: {
    currentPage: number
    pageSize: number
    total: number
    pageSizes?: number[]
    layout?: string
  }
  
  // 显示控制
  showToolbar?: boolean
  showRefresh?: boolean
  showColumnSettings?: boolean
  showPagination?: boolean
  showViewToggle?: boolean
  
  // 卡片视图布局
  cardLayout?: object
}

const props = withDefaults(defineProps<Props>(), {
  data: () => [],
  columns: () => [],
  loading: false,
  rowKey: 'id',
  defaultSort: undefined,
  pagination: () => ({
    currentPage: 1,
    pageSize: 20,
    total: 0,
    pageSizes: [10, 20, 30, 50, 100],
    layout: 'total, sizes, prev, pager, next, jumper'
  }),
  showToolbar: true,
  showRefresh: true,
  showColumnSettings: true,
  showPagination: true,
  showViewToggle: false,
  cardLayout: () => ({ xs: 24, sm: 12, md: 8, lg: 6 })
})

const emit = defineEmits<{
  (e: 'refresh'): void
  (e: 'sort-change', value: { prop: string; order: string }): void
  (e: 'selection-change', value: any[]): void
  (e: 'row-click', row: any, column: any, event: Event): void
  (e: 'size-change', value: number): void
  (e: 'current-change', value: number): void
  (e: 'view-mode-change', value: 'table' | 'card'): void
}>()

// 响应式数据
const tableRef = ref()
const viewMode = ref<'table' | 'card'>('table')
const showColumnSettingsDialog = ref(false)
const selectedColumns = ref<string[]>([])
const showAllColumns = ref(true)

// 计算属性
const tableData = computed(() => props.data || [])

const allColumns = computed(() => props.columns || [])

const visibleColumns = computed(() => {
  if (!selectedColumns.value.length) {
    return allColumns.value
  }
  return allColumns.value.filter((column: Column) => 
    selectedColumns.value.includes(column.prop || column.key || '') || column.fixed
  )
})

// 添加selectedRows计算属性
const selectedRows = computed(() => props.selectedItems || [])

const getColumnValue = (row: any, column: Column) => {
  // 添加调试日志
  console.log('getColumnValue called with:', { row, column });
  
  if (column.formatter) {
    const prop = column.prop || column.key || '';
    return column.formatter(row[prop], row, column, 0)
  }
  const prop = column.prop || column.key || '';
  
  // 优先级1: 直接匹配prop
  if (row[prop] !== undefined && row[prop] !== null) {
    console.log('直接找到prop:', prop, 'value:', row[prop]);
    return row[prop];
  }
  
  // 优先级2: 特殊处理供应商相关字段，优先使用驼峰命名
  if (prop === 'contactPerson') {
    // 优先使用contactPerson，如果没有则使用contact_person
    if (row['contactPerson'] !== undefined && row['contactPerson'] !== null) {
      console.log('通过contactPerson找到:', row['contactPerson']);
      return row['contactPerson'];
    }
    if (row['contact_person'] !== undefined && row['contact_person'] !== null) {
      console.log('通过contact_person找到:', row['contact_person']);
      return row['contact_person'];
    }
    return ''; // 默认返回空字符串而不是undefined
  }
  
  if (prop === 'cooperationDate') {
    // 优先使用cooperationDate，如果没有则使用cooperation_date
    if (row['cooperationDate'] !== undefined && row['cooperationDate'] !== null) {
      console.log('通过cooperationDate找到:', row['cooperationDate']);
      return row['cooperationDate'];
    }
    if (row['cooperation_date'] !== undefined && row['cooperation_date'] !== null) {
      console.log('通过cooperation_date找到:', row['cooperation_date']);
      return row['cooperation_date'];
    }
    return null;
  }
  
  if (prop === 'createdAt') {
    // 优先使用createdAt，如果没有则使用created_at
    if (row['createdAt'] !== undefined && row['createdAt'] !== null) {
      console.log('通过createdAt找到:', row['createdAt']);
      return row['createdAt'];
    }
    if (row['created_at'] !== undefined && row['created_at'] !== null) {
      console.log('通过created_at找到:', row['created_at']);
      return row['created_at'];
    }
    return null;
  }
  
  if (prop === 'updatedAt') {
    // 优先使用updatedAt，如果没有则使用updated_at
    if (row['updatedAt'] !== undefined && row['updatedAt'] !== null) {
      console.log('通过updatedAt找到:', row['updatedAt']);
      return row['updatedAt'];
    }
    if (row['updated_at'] !== undefined && row['updated_at'] !== null) {
      console.log('通过updated_at找到:', row['updated_at']);
      return row['updated_at'];
    }
    return null;
  }
  
  // 优先级3: 尝试将下划线命名转换为驼峰命名
  const camelCaseProp = prop.replace(/_([a-z])/g, (g) => g[1].toUpperCase());
  if (row[camelCaseProp] !== undefined && row[camelCaseProp] !== null) {
    console.log('通过驼峰命名找到:', camelCaseProp, 'value:', row[camelCaseProp]);
    return row[camelCaseProp];
  }
  
  // 优先级4: 尝试将驼峰命名转换为下划线命名
  const underscoreProp = prop.replace(/([A-Z])/g, '_$1').toLowerCase();
  if (row[underscoreProp] !== undefined && row[underscoreProp] !== null) {
    console.log('通过下划线命名找到:', underscoreProp, 'value:', row[underscoreProp]);
    return row[underscoreProp];
  }
  
  // 优先级5: 如果都没找到，返回默认值
  console.log('未找到对应值，返回默认值');
  // 根据字段类型返回合适的默认值
  if (prop === 'rating') {
    return '0.00';
  }
  if (prop === 'status') {
    return 'pending';
  }
  return row[prop] || ''; // 对于字符串字段返回空字符串
}

const getRowKey = (row: any, index: number) => {
  if (typeof props.rowKey === 'function') {
    return props.rowKey(row)
  }
  return row[props.rowKey] || index
}

// 方法
const handleRefresh = () => {
  emit('refresh')
}

const handleSelectionChange = (selection: any[]) => {
  emit('selection-change', selection)
}

const handleSortChange = ({ prop, order }: { prop: string; order: string }) => {
  emit('sort-change', { prop, order })
}

const handleRowClick = (row: any, column: any, event: Event) => {
  emit('row-click', row, column, event)
}

const handleCardClick = (row: any, index: number) => {
  // 卡片点击事件可以触发行点击
  emit('row-click', row, null, new Event('card-click'))
}

const handleSizeChange = (size: number) => {
  emit('size-change', size)
}

const handleCurrentChange = (page: number) => {
  emit('current-change', page)
}

const setViewMode = (mode: 'table' | 'card') => {
  viewMode.value = mode
  emit('view-mode-change', mode)
}

const toggleAllColumns = (checked: boolean) => {
  if (checked) {
    selectedColumns.value = allColumns.value
      .filter((col: Column) => !col.fixed)
      .map((col: Column) => col.prop || col.key || '')
  } else {
    selectedColumns.value = allColumns.value
      .filter((col: Column) => col.fixed)
      .map((col: Column) => col.prop || col.key || '')
  }
}

const applyColumnSettings = () => {
  showColumnSettingsDialog.value = false
  // 列设置应用后可以触发事件或保存到本地存储
}

// 初始化选中的列
onMounted(() => {
  // 初始化时选中所有列
  selectedColumns.value = allColumns.value
    .filter((col: Column) => col.visible !== false) // 过滤掉明确设置为不可见的列
    .map((col: Column) => col.prop || col.key || '')
  
  // 如果没有设置visible属性，默认都显示
  if (selectedColumns.value.length === 0) {
    selectedColumns.value = allColumns.value.map((col: Column) => col.prop || col.key || '')
  }
})

// 监听列变化
watch(() => props.columns, (newColumns: Column[]) => {
  selectedColumns.value = newColumns.map((col: Column) => col.prop || col.key || '')
}, { deep: true })
</script>

<script lang="ts">
export default {
  name: 'AdvancedTable',
  inheritAttrs: false
}
</script>

<style scoped lang="scss">
.advanced-table-container {
  .table-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding: 12px 0;
    
    .toolbar-left,
    .toolbar-right {
      display: flex;
      gap: 5px;
      align-items: center;
    }
    
    .toolbar-right {
      gap: 3px;
    }
  }
  
  .view-toggle-group {
    margin-left: 10px;
    
    .el-button {
      padding: 8px 12px;
    }
  }
  
  .table-view,
  .card-view {
    .table-pagination {
      display: flex;
      justify-content: flex-end;
      margin-top: 20px;
    }
  }
  
  .card-view {
    .card-item {
      margin-bottom: 16px;
      cursor: pointer;
      
      .card-field {
        display: flex;
        margin-bottom: 8px;
        
        .field-label {
          width: 100px;
          font-weight: 500;
          color: #606266;
        }
        
        .field-value {
          flex: 1;
          color: #303133;
        }
      }
    }
  }
  
  .column-settings {
    .select-all {
      margin-bottom: 16px;
    }
    
    :deep(.el-checkbox-group) {
      width: 100%;
      
      .el-col {
        margin-bottom: 12px;
      }
    }
  }
}
</style>